//
//  FileContentViewController.swift
//  Git@OSC
//
//  Created by AeternChan on 8/22/15.
//  Copyright (c) 2015 oschina. All rights reserved.
//

import UIKit
import WebKit

import Alamofire
import Mustache
import SwiftyJSON

class FileContentViewController: UIViewController {
    
    var url: String!
    var path: String!
    var isReadme = false
    
    
    @IBOutlet weak var webView: UIWebView!
//    var webView: WKWebView!
//    var webView: UIWebView!

    override func viewDidLoad() {
        
        super.viewDidLoad()
        navigationController?.interactivePopGestureRecognizer!.enabled = false
        if isReadme {navigationItem.title = "README"}
        
//        webView = WKWebView(frame: view.bounds)
//        webView = UIWebView(frame: view.bounds)
//        self.view.addSubview(webView)
        
        Alamofire.request(.GET, url, parameters: ["file_path": path, "ref": "master"])
            .responseJSON { response in
                
                if response.result.isSuccess {
                    let json = JSON(response.result.value!)
                    
                    let content = json["content"].stringValue
                    let data = [
                                "content": self.isReadme ? content : content.escapeHTMLTag(),
                                "style": NSUserDefaults.standardUserDefaults().objectForKey("style") as? String
                                ]
                    
                    let template = try! Template(named: "file_content")
                    let rendering = try! template.render(Box(data))
                    self.webView.loadHTMLString(rendering, baseURL: NSBundle.mainBundle().resourceURL)
                } else {
            
                }
        }
    }
}
